import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { DisseminationService } from '../dissemination-management.service';
import { PublicService } from 'app/public/public.service';
import { MESSAGE_CHANNEL, SELECT_OPTIONS } from 'app/app.constants';
import { BullySubjectService } from 'app/shared/service';

@Component({
    selector: 'itmp-message-template',
    templateUrl: './message-template.component.html',
    styleUrls: ['./message-template.component.css']
})
export class MessageTemplateComponent implements OnInit {
    search$ = new Subject<object>();
    pagination: any; // 分页数据的对象
    listOfData = null; // 列表数据的数组
    renderHeader = null; // 表头数据的数组
    toolbarList = [
        // 工具条栏
        // { className: 'icon-chakan' },
        // { className: 'icon-dingwei' },
        { className: 'icon-dayinfuyin-' }
        // { className: 'icon-screenfull' },
        // { className: 'icon-xiazai' }
    ];
    selectTemplate = null;
    // 筛选框下拉列表
    selectionList = {
        Equipment_Type: []
    };
    searchData: any;
    imgUrl: string;
    accessButton = {
        PRINT: false
    };
    isShowVietName = false;

    constructor(private diss: DisseminationService, private publicService: PublicService, private bully: BullySubjectService) {}

    ngOnInit() {
        this.searchPipeSet();
        this.selectionList.Equipment_Type = this.publicService.getSelectOptionsList(SELECT_OPTIONS.EQUIPMENT_TYPE).data;
        if (localStorage.getItem('itmp_lang') === 'vi') {
            this.selectionList.Equipment_Type.forEach(site => {
                site.displayName = site.vietName;
            });
        } else {
            this.selectionList.Equipment_Type.forEach(site => {
                site.displayName = site.name;
            });
        }
        this.changeLang();
        // this.selectionList.Equipment_Type = this.diss.typeArr;
        this.renderHeader = [
            {
                name: 'ID',
                key: null,
                value: 'template_id',
                isChecked: true
            },
            {
                name: 'Equipment_Type',
                key: null,
                value: 'device_type',
                isChecked: true
            },
            {
                name: 'Template_Name',
                key: null,
                value: 'template_name',
                isChecked: true
            }
        ];
        this.initData();
        this.getData();
        this.getButtonAccess();
        if (localStorage.getItem('itmp_lang') === 'vi') {
            this.isShowVietName = true;
        } else {
            this.isShowVietName = false;
        }
    }

    changeLang() {
        this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.LANGUAGE_CHANNEL).subscribe(res => {
            if (res.data === 'vi') {
                this.selectionList.Equipment_Type.forEach(site => {
                    site.displayName = site.vietName;
                });
            } else {
                this.selectionList.Equipment_Type.forEach(site => {
                    site.displayName = site.name;
                });
            }
        });
    }

    getButtonAccess() {
        this.accessButton = this.publicService.getButtonAccess('11', this.accessButton);
    }

    // 搜索(防抖)
    onSearch(name): void {
        this.search$.next({ name: this.searchData[name] });
    }

    // 防抖函数注册
    searchPipeSet() {
        this.search$.pipe(debounceTime(1000), distinctUntilChanged()).subscribe((kw: any) => {
            this.pagination.currentPage = 1;
            this.getData();
        });
    }

    // 获取数据
    getData() {
        for (const item in this.searchData) {
            if (this.searchData.hasOwnProperty(item)) {
                if (this.searchData[item] === '') {
                    this.searchData[item] = null;
                }
            }
        }
        if (this.searchData.device_type && typeof this.searchData.device_type === 'string') {
            this.searchData.device_type = this.diss.changeEqtType(this.searchData.device_type);
        }
        const params = {
            condition: this.searchData,
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        this.diss.getTemplateList(params).subscribe(res => {
            const content = res.data;
            if (!content) {
                this.listOfData = [];
                return;
            }
            this.listOfData = content.content;
            this.listOfData.forEach(item => {
                item.deviceType = this.diss.changeEqtType(item.deviceType);
            });
            this.pagination.currentSize = content.numberOfElements;
            this.pagination.totalEle = content.totolElements;
        });
    }

    // 初始化分页和搜索
    initData() {
        this.pagination = {
            totalEle: 10,
            pageSize: 10,
            currentPage: 1,
            currentSize: 10
        };
        this.searchData = {
            template_id: null,
            device_type: null,
            template_name: null
        };
        this.listOfData = [];
    }

    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getData();
    }

    onSizeChange(e) {
        this.pagination.pageSize = e;
        const total = this.pagination.totalEle;
        const curPage = this.pagination.currentPage;
        this.pagination.currentPage = Math.ceil(total / e) < curPage ? Math.ceil(total / e) : curPage;
        this.getData();
    }

    // 点击tr取值
    clickTR(i): void {
        this.listOfData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                data.active = true;
                this.selectTemplate = data;
                this.imgUrl = data.url;
            }
        });
    }

    // 刷新
    refresh(): void {
        // this.cancelActive();
        this.initData();
        this.getData();
        this.imgUrl = null;
        this.selectTemplate = null;
    }
}
